﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CustomControls;
using DataAccess;
using Model;
using Model.EntityModel;

namespace Project
{
    /// <summary>
    /// Interaction logic for ModifyComplaintPart2.xaml
    /// </summary>
    public partial class ModifyComplaintPart2 : UserControl
    {
        public long ComplaintId { get; set; }

        private List<FunctionaryInfo> EmployeesToAdd;
        public ModifyComplaintContent ModContentPrev { get; set; }

        public ModifyComplaintPart2(ModifyComplaintContent modifyComplaintPrev)
        {
            InitializeComponent();
            ModContentPrev = modifyComplaintPrev;
            lblCaseNumber.Content = ModContentPrev.lblCaseNumber.Content;
            lblRegistrationDate.Content = ModContentPrev.lblRegistrationDate.Content;
            tbIncidentDetail.AddValitationRule(new ShortStringRule(50));
            tbEvidenceDescription.AddValitationRule(new ShortStringRule(15));
            gridAddEvidence.Height = 0;
            ComplaintId = long.Parse(lblCaseNumber.Content.ToString());
            EmployeesToAdd = new List<FunctionaryInfo>();
            listBoxIntervinents.DataContext = EmployeesToAdd;
            LoadInformation();
        }

        private void LoadInformation()
        {
            var evidences = ComplaintDataAccess.GetAllEvidencesFromComplaint(ComplaintId);
            foreach (var evidence in evidences)
            {
                listBoxEvidences.Items.Add(evidence);
            }
            listBoxEvidences.UpdateLayout();
            tbIncidentDetail.Text = ComplaintDataAccess.GetComplaintById(ComplaintId).IncidentDetail;
            var employees = ComplaintDataAccess.GetAllEmployeeOfComplaintFromComp(ComplaintId);
            foreach (var employeeOfComplaint in employees)
            {
                if (employeeOfComplaint.Responsability == "Interviniente")
                {
                    var intervinent = EmployeeDataAccess.GetEmployeeByCi(employeeOfComplaint.CIEmployee);
                    EmployeesToAdd.Add(new FunctionaryInfo
                                                 {
                                                     CI = intervinent.CI,
                                                     Name =
                                                         intervinent.Name +" "+ intervinent.PaternalName +" "+
                                                         intervinent.MaternalName,
                                                     Rank = intervinent.Rank,
                                                     WorkingRole = intervinent.WorkingRole
                                                 });
                }
                if (employeeOfComplaint.Responsability == "Recepcionista")
                {
                    var recepter = EmployeeDataAccess.GetEmployeeByCi(employeeOfComplaint.CIEmployee);
                    lblRecepterName.Content = recepter.Name + " " + recepter.PaternalName + " " +
                                              recepter.MaternalName;
                    lblRecepterCi.Content = recepter.CI;
                    RecepterInfo.Visibility = Visibility.Visible;
                    lblRecepterError.Visibility = Visibility.Hidden;
                }
                if (employeeOfComplaint.Responsability == "Asignada")
                {
                    var asignedFuncionary = EmployeeDataAccess.GetEmployeeByCi(employeeOfComplaint.CIEmployee);
                    lblAsignedName.Content = asignedFuncionary.Name + " " + asignedFuncionary.PaternalName + " " +
                                              asignedFuncionary.MaternalName;
                    lblAsignedCi.Content = asignedFuncionary.CI;
                    AsignedInfo.Visibility = Visibility.Visible;
                    lblAsignedError.Visibility = Visibility.Hidden;
                }
                if (employeeOfComplaint.Responsability == "Jefe de Seguridad")
                {
                    var secBossFuncionary = EmployeeDataAccess.GetEmployeeByCi(employeeOfComplaint.CIEmployee);
                    lblSecBossName.Content = secBossFuncionary.Name + " " + secBossFuncionary.PaternalName + " " +
                                              secBossFuncionary.MaternalName;
                    lblSecBossCi.Content = secBossFuncionary.CI;
                    SecurityBossInfo.Visibility = Visibility.Visible;
                    lblSecBossError.Visibility = Visibility.Hidden;
                }
            }
            listBoxIntervinents.ItemsSource = EmployeesToAdd;
        }

        private void btnAddEvidence_Click(object sender, RoutedEventArgs e)
        {
            ShowDialogGrid();
            lblEvidenceNumber.Content = listBoxEvidences.Items.Count + 1;
            tbEvidenceDescription.Text = "";
            tbEvidenceDescription.IsEnabled = true;
            btnKeyEvidence.Visibility = Visibility.Hidden;
            btnAddSuccess.Content = "AGREGAR";
            btnAddSuccess.IsEnabled = true;
            tbEvidenceDescription.ToolTip = null;
        }

        private void ShowDialogGrid()
        {
            btnAddEvidence.IsHitTestVisible = false;
            tbEvidenceDescription.IsHitTestVisible = true;
            DoubleAnimation doubleAnimation = new DoubleAnimation(0, 196, new Duration(new TimeSpan(0, 0, 0, 0, 500)));
            Storyboard st = new Storyboard();
            st.Children.Add(doubleAnimation);
            Storyboard.SetTargetProperty(st, new PropertyPath("Height"));
            Storyboard.SetTargetName(st, "gridAddEvidence");
            BeginStoryboard(st);
        }

        private void HideDialogGrid()
        {
            btnAddEvidence.IsHitTestVisible = true;
            tbEvidenceDescription.IsHitTestVisible = false;
            DoubleAnimation doubleAnimation = new DoubleAnimation(196, 0, new Duration(new TimeSpan(0, 0, 0, 0, 500)));
            Storyboard st = new Storyboard();
            st.Children.Add(doubleAnimation);
            Storyboard.SetTargetProperty(st, new PropertyPath("Height"));
            Storyboard.SetTargetName(st, "gridAddEvidence");
            BeginStoryboard(st);
        }

        private void btnAddCancel_Click(object sender, RoutedEventArgs e)
        {
            HideDialogGrid();
            Validation.ClearInvalid(tbEvidenceDescription.GetBindingExpression(MaskTextBox.TextProperty));
            if (tbEvidenceDescription.Text.Length >= 15)
                lblEvidenceERROR.Visibility = Visibility.Hidden;
        }

        private void btnAddSuccess_Click(object sender, RoutedEventArgs e)
        {
            tbEvidenceDescription.GetBindingExpression(MaskTextBox.TextProperty).UpdateSource();
            bool hasError = Validation.GetHasError(tbEvidenceDescription);
            if (!hasError)
            {
                if (btnKeyEvidence.Visibility != Visibility.Visible)
                {
                    listBoxEvidences.Items.Add(new Evidence
                                                   {
                                                       IdComplaint = ComplaintId,
                                                       Number = int.Parse(lblEvidenceNumber.Content.ToString()),
                                                       Description = tbEvidenceDescription.Text
                                                   });
                }
                else
                {
                    if (tbEvidenceDescription.IsEnabled)
                    {
                        for (int i = 0; i < listBoxEvidences.Items.Count; i++)
                        {
                            var evi = (listBoxEvidences.Items[i] as Evidence);
                            if (evi.Number.ToString().Equals(lblEvidenceNumber.Content.ToString()))
                            {
                                (listBoxEvidences.Items[i] as Evidence).Description = tbEvidenceDescription.Text;
                            }
                        }
                    }
                }
                listBoxEvidences.UpdateLayout();
                HideDialogGrid();
                tbEvidenceDescription.Text = "";
                Validation.ClearInvalid(tbEvidenceDescription.GetBindingExpression(MaskTextBox.TextProperty));
                lblEvidenceERROR.Visibility = Visibility.Hidden;
                lblEvidencesError.Visibility = Visibility.Hidden;
            }
            else
            {
                lblEvidenceERROR.Visibility = Visibility.Visible;
            }
        }


        private void btnEdit_Click(object sender, RoutedEventArgs e)
        {
            Button cmd = (Button) sender;
            Evidence editme = (Evidence) cmd.DataContext;
            lblEvidenceNumber.Content = editme.Number;
            tbEvidenceDescription.Text = editme.Description;
            tbEvidenceDescription.IsEnabled = false;
            btnKeyEvidence.Visibility = Visibility.Visible;
            btnAddSuccess.Content = "GUARDAR";
            tbEvidenceDescription.ToolTip = "Para editar este campo necesita permisos especiales";
            btnAddSuccess.IsEnabled = false;
            if (string.IsNullOrEmpty(tbEvidenceDescription.Text))
                lblEvidenceERROR.Visibility = Visibility.Hidden;
            else
            {
                tbEvidenceDescription.GetBindingExpression(MaskTextBox.TextProperty).UpdateSource();
                if (tbEvidenceDescription.Text.Length >= 15)
                    lblEvidenceERROR.Visibility = Visibility.Hidden;
                else
                {
                    lblEvidenceERROR.Visibility = Visibility.Visible;
                }
            }
            ShowDialogGrid();
        }

        private void btnAddIntervinent_Click(object sender, RoutedEventArgs e)
        {
            SearchFunctionary searchFunctionary = new SearchFunctionary();
            searchFunctionary.allEmployees.Clear();
            searchFunctionary.employeesToShow = searchFunctionary.employeesToShow.Where(x => !EmployeesToAdd.Any(x1 => x1.CI == x.CI))
            .Union(EmployeesToAdd.Where(x => !searchFunctionary.employeesToShow.Any(x1 => x1.CI == x.CI))).ToList();
            searchFunctionary.listViewEmployees.DataContext = searchFunctionary.employeesToShow;
            searchFunctionary.listViewEmployees.Items.Refresh();
            searchFunctionary.listViewEmployees.MouseDoubleClick += EmployeeAdded;
            searchFunctionary.ShowDialog();
        }

        private void EmployeeAdded(object sender, MouseButtonEventArgs e)
        {
            var listbox = sender as ListBox;
            EmployeesToAdd.Add((listbox.SelectedValue as FunctionaryInfo));
            listBoxIntervinents.Items.Refresh();
            listBoxIntervinents.UpdateLayout();
            lblIntervinentsError.Visibility = Visibility.Hidden;
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            var style = new Style(typeof(Xceed.Wpf.Toolkit.MessageBox));
            style.Setters.Add(new Setter(Xceed.Wpf.Toolkit.MessageBox.YesButtonContentProperty, "Si"));
            var res = Xceed.Wpf.Toolkit.MessageBox.Show("Esta seguro(a) de que desea eliminar a la funcionaria de la lista?", "Confirmar Accion!", MessageBoxButton.YesNo, MessageBoxImage.Warning, style);
            if (res == MessageBoxResult.Yes)
            {
                Button cmd = (Button)sender;
                if (cmd.DataContext is FunctionaryInfo)
                {
                    FunctionaryInfo deleteme = (FunctionaryInfo)cmd.DataContext;
                    EmployeesToAdd.Remove(deleteme);
                    listBoxIntervinents.Items.Refresh();
                    listBoxEvidences.UpdateLayout();
                }
            }
        }

        private void btnSelectRecepter_Click(object sender, RoutedEventArgs e)
        {
            SearchFunctionary searchFunctionary = new SearchFunctionary();
            searchFunctionary.ShowDialog();
            var recepterFuncionary = searchFunctionary.listViewEmployees.SelectedValue as FunctionaryInfo;
            if (recepterFuncionary != null)
            {
                lblRecepterName.Content = recepterFuncionary.Name;
                lblRecepterCi.Content = recepterFuncionary.CI;
                RecepterInfo.Visibility = Visibility.Visible;
                lblRecepterError.Visibility = Visibility.Hidden;
            }
        }

        private void btnSelectAsigned_Click(object sender, RoutedEventArgs e)
        {
            SearchFunctionary searchFunctionary = new SearchFunctionary();
            searchFunctionary.ShowDialog();
            var asignedFuncionary = searchFunctionary.listViewEmployees.SelectedValue as FunctionaryInfo;
            if (asignedFuncionary != null)
            {
                lblAsignedName.Content = asignedFuncionary.Name;
                lblAsignedCi.Content = asignedFuncionary.CI;
                AsignedInfo.Visibility = Visibility.Visible; 
                lblAsignedError.Visibility = Visibility.Hidden;
            }
        }

        private void btnSelectSecBoss_Click(object sender, RoutedEventArgs e)
        {
            SearchFunctionary searchFunctionary = new SearchFunctionary();
            searchFunctionary.ShowDialog();
            var secBossFuncionary = searchFunctionary.listViewEmployees.SelectedValue as FunctionaryInfo;
            if (secBossFuncionary != null)
            {
                lblSecBossName.Content = secBossFuncionary.Name;
                lblSecBossCi.Content = secBossFuncionary.CI;
                SecurityBossInfo.Visibility = Visibility.Visible;
                lblSecBossError.Visibility = Visibility.Hidden;
            }
        }

        private void SaveAndContinue_Click(object sender, RoutedEventArgs e)
        {
            ModContentPrev.modComplaintpart2 = this;
            var par = this.Parent as ItemsControl;
            par.Items.Clear();
            par.Items.Add(ModContentPrev);
        }


        public List<Evidence> GatherEvidences()
        {
            List<Evidence> evidences = new List<Evidence>();
            foreach (var item in listBoxEvidences.Items)
            {
                evidences.Add(item as Evidence);
            }
            return evidences;
        }

        public List<FunctionaryInfo> GatherIntervinents()
        {
            List<FunctionaryInfo> intervinents = new List<FunctionaryInfo>();
            foreach (var item in listBoxIntervinents.Items)
            {
                intervinents.Add(item as FunctionaryInfo);
            }
            return intervinents;
        }

        private void SaveComplaint()
        {
            try
            {
                bool hasErrors = CheckHasErrors();
                if (!hasErrors)
                {
                    ModContentPrev.UpdateFirstPartComplaint(tbIncidentDetail.Text);
                    var evidences = GatherEvidences();
                    foreach (var evidence in evidences)
                    {
                        ComplaintDataAccess.UpdateEvidence(evidence);
                    }
                    var intervinents = GatherIntervinents();
                    var intervinentEmployees = new List<EmployeeOfComplaint>();
                    foreach (var interv in intervinents)
                    {
                        intervinentEmployees.Add(new EmployeeOfComplaint
                                                     {
                                                         CIEmployee = interv.CI,
                                                         IdComplaint = ComplaintId,
                                                         Responsability = "Interviniente"
                                                     });
                    }
                    ComplaintDataAccess.UpdateIntervinentsOfComplaint(intervinentEmployees, ComplaintId);

                    ComplaintDataAccess.UpdateEmployeeOfComplaint(new EmployeeOfComplaint { CIEmployee = long.Parse(lblRecepterCi.Content.ToString()), IdComplaint = ComplaintId, Responsability = "Recepcionista" });
                    ComplaintDataAccess.UpdateEmployeeOfComplaint(new EmployeeOfComplaint { CIEmployee = long.Parse(lblAsignedCi.Content.ToString()), IdComplaint = ComplaintId, Responsability = "Asignada" });
                    ComplaintDataAccess.UpdateEmployeeOfComplaint(new EmployeeOfComplaint { CIEmployee = long.Parse(lblSecBossCi.Content.ToString()), IdComplaint = ComplaintId, Responsability = "Jefe de Seguridad" });
                    var style = new Style(typeof(Xceed.Wpf.Toolkit.MessageBox));
                    style.Setters.Add(new Setter(Xceed.Wpf.Toolkit.MessageBox.YesButtonContentProperty, "Si"));
                    var resB = Xceed.Wpf.Toolkit.MessageBox.Show("La denuncia se modificó exitosamente, tome nota, el numero de Denuncia es: " + lblCaseNumber.Content + ". Desea imprimir la denuncia?",
                                                                "Exito!", MessageBoxButton.YesNo,
                                                                MessageBoxImage.Information, style);
                    if (resB == MessageBoxResult.Yes)
                    {
                        var items = new ObservableCollection<UserControl>();
                        items.Add(new PrintComplaint(ComplaintId));
                        items.Add(new PrintComplaintPart2(ComplaintId));
                        items.Add(new PrintComplaintPart3(ComplaintId));
                        var a = new PrintPreviewDialogV2(items);
                        a.ShowDialog();
                    }
                    else
                    {
                        Xceed.Wpf.Toolkit.MessageBox.Show("Puede imprimir la denuncia posteriormente, entrando a Ver Denuncias, click sobre la denuncia selecciona la opción Ver Denuncia",
                                                                "Información!", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    UIWindowManager.CleanWindow(this);
                }
                else
                {
                    Xceed.Wpf.Toolkit.MessageBox.Show("Se deben llenar todos los campos indicados para poder continuar!", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (UpdateException)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Hubo un problema al guardar los datos en la base de datos!", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (EntitySqlException)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Hubo un problema al guardar los datos en la base de datos!", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (SqlException)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Hubo un problema al guardar los datos en la base de datos!", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Ocurrio un error desconocido, no se modificó la denuncia!", "Error!");
            }
        }

        private bool CheckHasErrors()
        {
            bool res = false;
            tbIncidentDetail.GetBindingExpression(MaskTextBox.TextProperty).UpdateSource();
            if (Validation.GetHasError(tbIncidentDetail))
                res = true;
            if (listBoxEvidences.Items.Count == 0)
            {
                lblEvidencesError.Visibility = Visibility.Visible;
                res = true;
            }
            if (listBoxIntervinents.Items.Count == 0)
            {
                lblIntervinentsError.Visibility = Visibility.Visible;
                res = true;
            }
            if (string.IsNullOrEmpty(lblRecepterName.Content.ToString()))
            {
                lblRecepterError.Visibility = Visibility.Visible;
                res = true;
            }
            if (string.IsNullOrEmpty(lblAsignedName.Content.ToString()))
            {
                lblAsignedError.Visibility = Visibility.Visible;
                res = true;
            }
            if (string.IsNullOrEmpty(lblSecBossName.Content.ToString()))
            {
                lblSecBossError.Visibility = Visibility.Visible;
                res = true;
            }
            return res;
        }

        private void btnRegister_Click(object sender, RoutedEventArgs e)
        {
            SaveComplaint();
        }

        private void BtnKeyEvidence_OnClick(object sender, RoutedEventArgs e)
        {
            var grantPermission = new GrantDirectorPermissionWindows();
            if (grantPermission.ShowDialog() == true)
            {
                tbEvidenceDescription.IsEnabled = true;
            }
        }

        private void tbEvidenceDescription_TextChanged(object sender, TextChangedEventArgs e)
        {
            if(tbEvidenceDescription.Text.Length>=15)
                lblEvidenceERROR.Visibility = Visibility.Hidden;
            if (btnKeyEvidence.Visibility == Visibility.Visible)
                btnAddSuccess.IsEnabled = true;
        }
    }
}
